package linkedList;
//需要在尾节点停住的话就while(cur.next != null) 需要把整个链表走完的话就while(cur != null)
public class LinkedList implements MyLinkedList{
    class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    public ListNode head;
    @Override
    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        node.next = this.head;
        this.head = node;
    }

    @Override
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        if(this.head == null){
            this.head = node;
        }else {
            ListNode cur = this.head;
            while (cur.next != null){
                cur = cur.next;
            }
            cur.next = node;
        }
    }

    //把第一个节点看为0号
    @Override
    public void addIndex(int index, int data) {
        if(index > size() || index < 0){
            throw new IndexIllegalException("下标不合法");
        }
        ListNode node = new ListNode(data);
        ListNode cur = head;
        for(int i = 1; i < index; i++ ){
            cur = cur.next;
        }
        node.next = cur.next;
        cur.next = node;

    }

    @Override
    public boolean contains(int key) {
        ListNode cur = head;
        while (cur != null){
            if(cur.val == key){
                return true;
            }else {
                cur = cur.next;
            }
        }

        return false;
    }

    @Override
    public void remove(int key) {
        if(head ==null){
            return;
        }
        ListNode cur = this.head;
        if(cur.val == key){
            head = cur.next;
            return;
        }
        while (cur.next != null){
            if (cur.next.val == key){
                cur = cur.next.next;
                return;
            }
            cur = cur.next;
        }
        throw new  RuntimeException("没有这个值");
    }

    @Override
    public void removeAllKey(int key) {
        if(head == null){
            return;
        }
        ListNode cur = head.next;
        ListNode preCur = head;
        while (cur != null){
           if(cur.val == key){
               preCur.next = cur.next;
               cur = cur.next;
           }else {
               preCur = cur;
               cur = cur.next;
           }
        }
        if(head.val == key){
            head = head.next;
        }
    }

    @Override
    public int size() {
        int count = 0;
        ListNode cur = this.head;
        while (cur.next != null){
            count++;
            cur = cur.next;
        }
        return count;
    }

    @Override
    public void clear() {
        this.head = null;
    }

    @Override
    public void display() {
        ListNode cur = this.head;
        while (cur.next != null){
            System.out.println(cur.val);
            cur = cur.next;
        }
    }
}
